//
//  ArrayViewController.m
//  FLORIDA
//
//  Created by 魏延(颜魏) on 2023/8/1.
//

#import "ArrayViewController.h"
#import "BatteryTableViewCell.h"
#import "DeviceSelectListViewController.h"
#import "CreatGroupViewController.h"
#import "BlutoothGroupModel.h"
#import "BTManager.h"
#import "ProgressHUD.h"

@interface ArrayViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *itemWidth;
@property (weak, nonatomic) IBOutlet UIView *addView;
@property (weak, nonatomic) IBOutlet UITableView *currentTab;
@property (weak, nonatomic) IBOutlet UITableView *groupTab;
@property (strong, nonatomic) IBOutletCollection(UIView) NSArray *segItemViews;

@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, assign) BOOL currentShow;
@property (nonatomic, strong) NSMutableArray *batteryShows;
@property (nonatomic, strong) NSMutableArray<BlutoothGroupModel *> *groupBatterys;
@property (nonatomic, strong) BlutoothGroupModel *currentGroup;
@property (nonatomic, assign) BOOL needQuery;
@property (nonatomic, assign) BOOL isChanged;

@end

@implementation ArrayViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData1) name:kBTBluGroupChanged object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDevice) name:kBTSearchDevices object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getBatteryLevel:) name:kBTGetBatteryLevel object:nil];

    self.itemWidth.constant = kWidth;
    self.currentShow = YES;
    self.needQuery = YES;
    self.isChanged = NO;
    self.batteryShows = [[NSMutableArray alloc] init];
    self.groupBatterys = [[NSMutableArray alloc] init];

    self.currentTab.separatorInset = UIEdgeInsetsZero;
    self.groupTab.separatorInset = UIEdgeInsetsZero;
    self.currentTab.separatorColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    self.groupTab.separatorColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    [self.currentTab registerNib:[UINib nibWithNibName:@"BatteryTableViewCell" bundle:nil] forCellReuseIdentifier:@"BatteryTableViewCell"];
    [self.groupTab registerNib:[UINib nibWithNibName:@"BatteryTableViewCell" bundle:nil] forCellReuseIdentifier:@"BatteryTableViewCell"];
    if (@available(iOS 15.0, *)) {
        self.currentTab.sectionHeaderTopPadding = 0;
        self.groupTab.sectionHeaderTopPadding = 0;
    }
    
    [self.addView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionAddBlue)]];
    
    [self reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self reloadDevice];
}

- (void)reloadDevice {
    NSMutableArray *blues = [NSMutableArray array];
    for (BlutoothGroupModel *group in self.groupBatterys) {
        [blues addObjectsFromArray:group.bluList];
    }
    NSMutableArray *connectBlues = [NSMutableArray array];
    for (BlutoothModel *blu in blues) {
        for (CBPeripheral *p in [BTManager sharedBTManager].peripherals) {
            if ([p.name isEqualToString:blu.name]) {
                [connectBlues addObject:p];
                break;
            }
        }
    }
    NSArray *arr = [NSMutableArray arrayWithArray:[BTManager sharedBTManager].lookSocBlues];
    [BTManager sharedBTManager].lookSocBlues = connectBlues;
    if (!self.showCurrentPage) {
        return;
    }
    if (!self.needQuery) {
        self.needQuery = YES;
        return;
    }
    if (![BTManager sharedBTManager].isGettingBattery || arr.count != connectBlues.count || self.isChanged) {
        self.isChanged = NO;
        [BTManager sharedBTManager].isGettingBattery = YES;
    }
}

- (void)reloadData1 {
    self.needQuery = NO;
    self.isChanged = YES;
    [self reloadData];
}

- (void)reloadData {
//    [[BTManager sharedBTManager].batteryLevelSource removeAllObjects];
    [self.groupBatterys removeAllObjects];
    self.currentGroup = nil;
    [self.batteryShows removeAllObjects];
    
    NSString *groupStr = [[NSUserDefaults standardUserDefaults] objectForKey:BatteryGroupBluList] ?: @"";
    if (groupStr.length) {
        NSArray *dataArray = [BlutoothGroupModel jsonCovertToModel:groupStr];
        NSMutableArray *mlist = [NSMutableArray array];
        for (BlutoothGroupModel *model in dataArray) {
            if (model.bluList.count == 0) {
                [mlist addObject:model];
            }else {
                [mlist addObject:model];
            }
        }
        [self.groupBatterys addObjectsFromArray:mlist];
    }
    for (BlutoothGroupModel *model in self.groupBatterys) {
        [self.batteryShows addObject:@(NO)];
    }
    if (self.batteryShows.count) {
        [self.batteryShows replaceObjectAtIndex:0 withObject:@(YES)];
    }
    
    [self.currentTab reloadData];
    [self.groupTab reloadData];
    [self reloadDevice];
}

- (void)reloadUI {
    [self.currentTab reloadData];
    [self.groupTab reloadData];
}

- (void)actionAddBlue {
    DeviceSelectListViewController *vc = [[DeviceSelectListViewController alloc] initWithNibName:@"DeviceSelectListViewController" bundle:nil];
    [self.nv pushViewController:vc animated:YES];
}

- (void)actionHead:(UITapGestureRecognizer *)tap {
    NSInteger index = tap.view.tag - 100;
    if(self.currentIndex == 0) {
        self.currentShow = !self.currentShow;
        [self.currentTab reloadData];
    }else {
        [self.batteryShows replaceObjectAtIndex:index withObject:@(![self.batteryShows[index] boolValue])];
        [self.groupTab reloadData];
    }
}

- (void)actionMore:(UIButton *)btn {
    NSInteger index = btn.tag - 1000;
    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Delete Group" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self actionGroupMore:index type:0];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Rename Group" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self actionGroupMore:index type:1];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Close" style:UIAlertActionStyleDestructive handler:nil]];
    [self presentViewController:sheet animated:YES completion:nil];
}

- (void)actionGroupMore:(NSInteger)index type:(NSInteger)type {
    if(type == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"Delete Group?" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDestructive handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *groupStr = [[NSUserDefaults standardUserDefaults] objectForKey:BatteryGroupBluList] ?: @"";
            NSMutableArray *dataArray = [NSMutableArray arrayWithArray:[BlutoothGroupModel jsonCovertToModel:groupStr]];
            for (BlutoothGroupModel *model in dataArray) {
                NSString *groupId = (self.currentIndex == 0) ? self.currentGroup.groupId : self.groupBatterys[index].groupId;
                if ([model.groupId isEqualToString:groupId]) {
                    [dataArray removeObject:model];
                    break;
                }
            }
            NSString *str = [BlutoothGroupModel toJson:dataArray];
            [[NSUserDefaults standardUserDefaults] setObject:str forKey:BatteryGroupBluList];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [ProgressHUD showActivityMessageInView:@""];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [ProgressHUD hideHUD];
                [ProgressHUD showSuccessMessage:@"Delete successfully"];
                [self reloadData];
                if (self.currentIndex == 0) {
                    [self.navigationController popToRootViewControllerAnimated:NO];
                    [[BTManager sharedBTManager] disconnectRootPeripheral];
                }
            });
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }else {
        CreatGroupViewController *vc = [[CreatGroupViewController alloc] initWithNibName:@"CreatGroupViewController" bundle:nil];
        vc.group = (self.currentIndex == 0) ? self.currentGroup : self.groupBatterys[index];
        vc.type = 1;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)actionItemMore:(NSInteger)section row:(NSInteger)row {
    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Delete battery" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self actionBatteryOpt:section row:row type:0];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Rename battery" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self actionBatteryOpt:section row:row type:1];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Check battery" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self actionBatteryOpt:section row:row type:2];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Close" style:UIAlertActionStyleDestructive handler:nil]];
    [self presentViewController:sheet animated:YES completion:nil];
}

- (void)actionBatteryOpt:(NSInteger)section row:(NSInteger)row type:(NSInteger)type {
    if(type == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"Delete battery?" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDestructive handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *groupStr = [[NSUserDefaults standardUserDefaults] objectForKey:BatteryGroupBluList] ?: @"";
            NSArray *dataArray = [BlutoothGroupModel jsonCovertToModel:groupStr];
            NSString *bluName = @"";
            for (BlutoothGroupModel *model in dataArray) {
                NSString *groupId = (self.currentIndex == 0) ? self.currentGroup.groupId : self.groupBatterys[section].groupId;
                if ([model.groupId isEqualToString:groupId]) {
                    NSMutableArray<BlutoothModel *> *arr = [NSMutableArray arrayWithArray:model.bluList];
                    bluName = arr[row].name;
                    [arr removeObjectAtIndex:row];
                    model.bluList = arr;
                    break;
                }
            }
            NSString *str = [BlutoothGroupModel toJson:dataArray];
            [[NSUserDefaults standardUserDefaults] setObject:str forKey:BatteryGroupBluList];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [ProgressHUD showActivityMessageInView:@""];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [ProgressHUD hideHUD];
                [ProgressHUD showSuccessMessage:@"Delete successfully"];
                if (self.currentIndex == 0 && [bluName isEqualToString:[BTManager sharedBTManager].peripheral.name]) {
                    [self.navigationController popToRootViewControllerAnimated:NO];
                    [[BTManager sharedBTManager] disconnectRootPeripheral];
                }else {
                    [self reloadData];
                }
            });
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }else if(type == 1) {
        [self actionItemEdit:section row:row];
    }else {
        BlutoothModel *blue = (self.currentIndex == 0) ? self.currentGroup.bluList[row] : self.groupBatterys[section].bluList[row];
        self.clickConnectBlueBlock(blue);
    }
}

- (void)actionItemEdit:(NSInteger)section row:(NSInteger)row {
    CreatGroupViewController *vc = [[CreatGroupViewController alloc] initWithNibName:@"CreatGroupViewController" bundle:nil];
    vc.battery = (self.currentIndex == 0) ? self.currentGroup.bluList[row] : self.groupBatterys[section].bluList[row];
    vc.group = (self.currentIndex == 0) ? self.currentGroup : self.groupBatterys[section];
    vc.type = 2;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [tableView isEqual:self.currentTab] ? (self.currentGroup ? 1 : 0) : self.groupBatterys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:self.currentTab]) {
        return self.currentShow ? self.currentGroup.bluList.count : 0;
    }else {
        return [self.batteryShows[section] boolValue] ? self.groupBatterys[section].bluList.count : 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BatteryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BatteryTableViewCell"];
    WeakSelf
    cell.clickMore = ^{
        [weakSelf actionItemMore:indexPath.section row:indexPath.row];
    };
    cell.clickEdit = ^{
        [weakSelf actionItemEdit:indexPath.section row:indexPath.row];
    };
    if ([tableView isEqual:self.currentTab]) {
        cell.model = self.currentGroup.bluList[indexPath.row];
    }else {
        cell.model = self.groupBatterys[indexPath.section].bluList[indexPath.row];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 54;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 54;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 54)];
    headView.backgroundColor = [UIColor clearColor];
    headView.tag = 100 + section;
    [headView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionHead:)]];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 200, 54)];
    label.text = [tableView isEqual:self.currentTab] ? self.currentGroup.groupName : self.groupBatterys[section].groupName;
    label.font = [UIFont systemFontOfSize:16];
    label.textColor = [UIColor whiteColor];
    [headView addSubview:label];
    
    UIButton *moreBtn = [[UIButton alloc] initWithFrame:CGRectMake(kWidth-60, 0, 60, 54)];
    [moreBtn setImage:[UIImage imageNamed:@"more_icon"] forState:UIControlStateNormal];
    moreBtn.tag = section + 1000;
    [moreBtn addTarget:self action:@selector(actionMore:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:moreBtn];
    
    UIImageView *arrowIV = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth-60-15, 17, 20, 20)];
    if ([tableView isEqual:self.currentTab]) {
        arrowIV.image = [UIImage imageNamed:self.currentShow ? @"show_more" : @"show_more_1"];
    }else {
        arrowIV.image = [UIImage imageNamed:[self.batteryShows[section] boolValue] ? @"show_more" : @"show_more_1"];
    }
    [headView addSubview:arrowIV];

    UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0, 53.5, kWidth, 0.5)];
    line.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.2];
    [headView addSubview:line];

    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 0.001)];
    return footView;
}

- (void)getBatteryLevel:(NSNotification *)nf {
    [self.currentTab reloadData];
    [self.groupTab reloadData];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isEqual:self.currentTab] || [scrollView isEqual:self.groupTab]) {
        return;
    }
    CGFloat index = scrollView.contentOffset.x/kWidth;
    self.currentIndex = (NSInteger)index;
    for (NSInteger i=0; i<self.segItemViews.count; i++) {
        UIView *view = self.segItemViews[i];
        view.backgroundColor = (NSInteger)index == i ? SUBJECT_COLOR : [UIColor lightGrayColor];
    }
}

@end
